import React from 'react';
import { Tools, Tabs, Bubble } from 'weaver-mobile';
import { forwardViewForm } from '../../../../workflowForm/util/forwardPage';
import * as API_HOMEPAGE from '../../../apis/homepage';
import Loading from '../Loading';
import Doc from './doc';
import Workflow from './workfow';
import CustomPage from './custompage';
import Chart from './chart';

class MultiTabElement extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.onLoadMore = this.onLoadMore.bind(this);
    this.onWfFormOpen = this.onWfFormOpen.bind(this);
    this.onDocDetailOpen = this.onDocDetailOpen.bind(this);
    this.state = {
      loading: false,
      visible2: false,
      loading2: false,
      tab: {},
      tabid: 0,
      pageIndex: 1,
      moreUrl: '',
      result: {}
    };
  }

  componentWillMount() {
    const { tabs } = this.props;
    if (tabs && tabs.length) {
      this.onLoadData(tabs[0]);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.refreshing) {
      const { tabs } = nextProps;
      if (tabs && tabs.length) {
        this.onLoadData(tabs[0]);
      }
    }
  }

  render() {
    const { ebaseid, tabs } = this.props;
    const { loading, visible2, loading2, tabid, result } = this.state;

    let tabComp = null;
    if (tabs && tabs.length > 1) {
      let page = 0;
      for (let i = 0, len = tabs.length; i < len; i++) {
        if (tabs[i].tabid === tabid) {
          page = i;
          break;
        }
      }
      tabComp = <Tabs tabs={tabs} page={page} renderTabBar={props => <Tabs.ExpandTabBar {...props} fix={8} />} onTabClick={item => this.onLoadData(item)} />;
    }

    let eComp = null;
    switch (ebaseid) {
      case '7':
        eComp = <Doc result={result} onClick={this.onDocDetailOpen} />;
        break;
      case '8':
        eComp = <Workflow result={result} onClick={this.onWfFormOpen} />;
        break;
      case '29':
        eComp = <CustomPage result={result} />;
        break;
      case 'reportForm':
        eComp = <Chart result={result} />;
        break;
    }
    let dataComp = (
      <div className="data">
        <Loading loading={loading}>{eComp}</Loading>
      </div>
    );

    let moreComp = null;
    if (visible2) {
      moreComp = (
        <div className="more">
          <Loading loading={loading2}>
            <div className="icon-more" onClick={this.onLoadMore} />
          </Loading>
        </div>
      );
    }

    return (
      <div className="content">
        {tabComp}
        {dataComp}
        {moreComp}
      </div>
    );
  }

  onLoadData(tab) {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const { tabid } = tab;
    const params = { hpid, subCompanyId, eid, ebaseid, tabId: tabid };

    if (ebaseid == '29') {
      // 自定义页面
      this.setState({ loading: true, visible2: false, tabid, pageIndex: 1 });

      const { url, moreUrl } = tab;
      if (/^(http|https):\/\/([\w.]+\/?)\S*/.test(url) || url == '/mobile/plugin/4/index.jsp' || url == '/mobilemode/appHomepageView.jsp?appHomepageId=335') {
        this.setState({ loading: false, result: { src: url } });
      } else {
        Tools.callApi({ url: url, method: 'GET', type: 'text' }).then(result => {
          this.setState({
            loading: false,
            visible2: !!moreUrl,
            moreUrl: moreUrl,
            result: { html: result }
          });
        });
      }
    } else {
      const result = localStorage.getItem(`portal-element-${eid}-${tabid}`);
      this.setState({
        loading: true,
        visible2: false,
        tab: tab,
        tabid: tabid,
        pageIndex: 1,
        result: result ? JSON.parse(result) : {}
      });

      API_HOMEPAGE.getElementData(params).then(result => {
        const { data, showType } = result;
        let visible2 = !!(data && data.length);
        if (ebaseid == '7' && showType == '5') {
          visible2 = false;
        }
        this.setState({
          loading: false,
          visible2: visible2,
          result: result
        });

        localStorage.setItem(`portal-element-${eid}-${tabid}`, JSON.stringify(result));
      });
    }
  }

  onLoadMore() {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const { tabid, pageIndex, moreUrl, result: _result } = this.state;
    const params = { hpid, subCompanyId, eid, ebaseid, tabId: tabid, pageIndex: pageIndex + 1 };

    this.setState({ loading2: true, pageIndex: pageIndex + 1 });

    if (ebaseid == '29') {
      // 自定义页面
      let url = '';
      if (moreUrl.indexOf('?') != -1) {
        url = moreUrl + `&pageIndex=${pageIndex + 1}`;
      } else {
        url = moreUrl + `?pageIndex=${pageIndex + 1}`;
      }
      Tools.callApi({ url: url, method: 'GET', type: 'text' }).then(result => {
        this.setState({
          loading2: false,
          result: { html: result }
        });
      });
    } else {
      API_HOMEPAGE.getElementData(params).then(result => {
        const { data = [] } = result;
        const { data: oldData } = _result;
        const newData = oldData.concat(data);
        this.setState({
          visible2: data.length > 0,
          loading2: false,
          result: { ..._result, data: newData }
        });
      });
    }
  }

  onWfFormOpen(requestid) {
    forwardViewForm(
      `requestid=${requestid}`,
      () => {
        const { tab } = this.state;
        this.onLoadData(tab);
      },
      'portal'
    );
  }

  onDocDetailOpen(docid) {
    const url = `/spa/document/static4mobile/index.html#/doc/${docid}`;

    if (window.em && window.em.checkJsApi('openLink')) {
      window.em.openLink({
        sysId: window.localStorage.emobile_ec_id,
        url: url,
        openType: 2
      });
    } else {
      window.open(url);
    }
  }
}

export default MultiTabElement;
